<template>
  <div class="container">
    <div class="container-content">
      <vab-query-form>
        <vab-query-form-top-panel v-show="data.showSearch">
          <el-form
            ref="queryRef"
            :model="tableOptions.queryForm"
            :inline="true"
            label-width="10"
            label-suffix=""
            style="padding-right: 10px"
            @keyup.enter="queryTableData"
          >
            <el-form-item prop="initiatorId" label="">
              <CommonSelect
                v-model:defaultValue="tableOptions.queryForm.initiatorId"
                :placeholder="translate('flow.inst.initiatorId')"
                label="userName"
                value="id"
                url="/admin/sysuser/getlist"
              />
            </el-form-item>
            <el-form-item prop="defFlowId">
              <CommonSelect
                v-model:defaultValue="tableOptions.queryForm.defFlowId"
                :placeholder="translate('flow.inst.defFlowId')"
                label="flowName"
                value="id"
                url="/esflow/def/getlist"
              />
            </el-form-item>
            <el-form-item prop="flowNodeId">
              <CommonSelect
                v-model:defaultValue="tableOptions.queryForm.flowNodeId"
                :placeholder="translate('flow.inst.flowNodeId')"
                label="nodeName"
                value="id"
                url="/esflow/def/node/getlist"
              />
            </el-form-item>
            <el-form-item prop="nodeJobId">
              <CommonSelect
                v-model:defaultValue="tableOptions.queryForm.nodeJobId"
                :placeholder="translate('flow.inst.nodeJobId')"
                label="jobName"
                value="id"
                url="/esflow/def/job/getlist"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                icon="Refresh"
                type="warning"
                @click="handleResetQuery"
              >
                {{ translate("buttons.reset") }}</el-button
              >
              <el-button icon="search" type="primary" @click="queryTableData">
                {{ translate("buttons.search") }}
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-top-panel>
        <vab-query-form-left-panel />
        <vab-query-form-right-panel>
          <RightToolBar
            v-model:showSearch="data.showSearch"
            :export="false"
            @refresh="queryTableData"
            @toggle="handleToggleSearch"
          />
        </vab-query-form-right-panel>
      </vab-query-form>
      <el-table
        ref="tableRef"
        v-loading="tableOptions.loading"
        border
        :data="tableOptions.dataList"
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        :height="tableOptions.height"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="handleSortChange"
      >
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column
          prop="initiatorId"
          label="申请人"
          show-overflow-tooltip
          width="120"
        >
          <template #default="scope">
            {{
              scope.row.runFlow && scope.row.runFlow.initiatorName
                ? scope.row.runFlow.initiatorName
                : scope.row.runFlow.initiatorId
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderInstCode"
          label="工单编号"
          show-overflow-tooltip
          width="210"
        />
        <el-table-column
          prop="defFlowId"
          label="流程名称"
          show-overflow-tooltip
          width="160"
        >
          <template #default="scope">
            {{
              scope.row.runFlow && scope.row.runFlow.flowName
                ? scope.row.runFlow.flowName
                : scope.row.flowInstId
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="flowInstId"
          label="流程实例"
          show-overflow-tooltip
          width="180"
        />
        <el-table-column
          prop="flowNodeId"
          label="节点名称"
          show-overflow-tooltip
          width="160"
        >
          <template #default="scope">
            {{
              scope.row.runNode && scope.row.runNode.nodeName
                ? scope.row.runNode.nodeName
                : scope.row.flowNodeId
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="jobName"
          label="任务名称"
          show-overflow-tooltip
          width="160"
        />
        <el-table-column
          prop="jobTypeDesc"
          label="办理人类型"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          prop="roleName"
          label="办理角色"
          show-overflow-tooltip
          width="100"
        />
        <el-table-column
          prop="userName"
          label="办理人"
          show-overflow-tooltip
          width="100"
        />
        <el-table-column
          prop="startTime"
          label="开始时间"
          show-overflow-tooltip
          width="160"
        />
        <el-table-column
          prop="endTime"
          label="办理时间"
          show-overflow-tooltip
          width="160"
        />
        <el-table-column
          prop="timeLimit"
          label="截止时间"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          prop="useTime"
          label="耗时"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          prop="statusDesc"
          label="任务状态"
          show-overflow-tooltip
          width="100"
        />
        <el-table-column
          prop="suspensionDesc"
          label="挂起"
          show-overflow-tooltip
          width="80"
        />
        <el-table-column
          prop="executeModeDesc"
          label="执行模式"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            {{
              scope.row.runNode && scope.row.runNode.executeModeDesc
                ? scope.row.runNode.executeModeDesc
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="parallelModeDesc"
          label="并行模式"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            {{
              scope.row.runNode && scope.row.runNode.parallelModeDesc
                ? scope.row.runNode.parallelModeDesc
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="isReadDesc"
          label="已读"
          show-overflow-tooltip
          width="80"
        />
        <el-table-column
          prop="suspensionReason"
          label="任务暂停原因"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          prop="invalidReason"
          label="流程作废原因"
          show-overflow-tooltip
          width="120"
        >
          <template #default="scope">
            {{
              scope.row.runFlow && scope.row.runFlow.invalidReason
                ? scope.row.runFlow.invalidReason
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="flowStatusDesc"
          label="流程状态"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            {{
              scope.row.runFlow && scope.row.runFlow.flowStatusDesc
                ? scope.row.runFlow.flowStatusDesc
                : scope.row.flowInstId
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="parFlowInstId"
          label="父流程名称"
          show-overflow-tooltip
          width="160"
        >
          <template #default="scope">
            {{
              scope.row.parRunFlow && scope.row.parRunFlow.flowName
                ? scope.row.parRunFlow.flowName
                : scope.row.parFlowInstId
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="subDefFlowId"
          label="子流程名称"
          show-overflow-tooltip
          width="160"
        >
          <template #default="scope">
            {{
              scope.row.subRunFlow && scope.row.subRunFlow.flowName
                ? scope.row.subRunFlow.flowName
                : scope.row.subFlowInstId
            }}
          </template>
        </el-table-column>
        <el-table-column :label="translate('操作')" width="180" fixed="right">
          <template #default="scope">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <el-dropdown style="margin-right: 10px; vertical-align: middle">
                <el-button icon="ArrowDown" text type="primary">
                  功能
                  <arrow-down />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="methods.handleComment(scope.row)"
                      >查看审批过程</el-dropdown-item
                    >
                    <el-dropdown-item
                      divided
                      @click="methods.handleFlowPic(scope.row)"
                      >查看流程图</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="!scope.row.userId"
                      divided
                      @click="methods.handleSignOnJob(scope.row)"
                    >
                      签收任务
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.userId === userStore.userid"
                      divided
                      @click="methods.handleSignOffJob(scope.row)"
                    >
                      反签收任务
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.suspension === '1'"
                      divided
                      @click="methods.handleSuspension(scope.row, '0')"
                    >
                      激活任务
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.suspension !== '1'"
                      divided
                      @click="methods.handleSuspension(scope.row, '1')"
                    >
                      挂起任务
                    </el-dropdown-item>
                    <el-dropdown-item
                      divided
                      @click="methods.handleTurnJob(scope.row)"
                      >转办任务</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button
                v-if="
                  scope.row.suspension !== '1' &&
                  (scope.row.status === '0' || scope.row.status === '9')
                "
                icon="Stamp"
                text
                type="primary"
                @click="methods.handleJob(scope.row, true)"
              >
                审批
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="tableOptions.pagination.current"
        :layout="tableOptions.pagination.layout"
        :page-size="tableOptions.pagination.size"
        :total="tableOptions.pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
      <CommonDialog
        v-model="data.showHandleJob"
        title="办理任务"
        :close-on-click-modal="true"
        fullscreen
        append-to-body
        :show-footer="true"
        :showFooterOk="false"
        cancelText="关闭"
        @cancel="data.showHandleJob = false"
        @closed="data.showHandleJob = false"
      >
        <HandleJob
          :curr-job="data.job"
          @complete="methods.onHandleJobComplete"
        />
      </CommonDialog>
      <AuditorChoose
        ref="auditorChooseRef"
        :appointType="data.appointType"
        @confirm="methods.handleAuditorConfirm"
      />

      <CommonDialog
        v-model="data.showComment"
        width="60%"
        title="审批过程"
        append-to-body
        :show-footer="false"
        @cancel="data.showComment = false"
        @closed="data.showComment = false"
      >
        <CommentTimeLine
          :flow-inst-id="data.currJob.flowInstId"
          @close="data.showComment = false"
        />
      </CommonDialog>

      <CommonDialog
        v-if="mounted"
        v-model="data.showFlowPic"
        width="60%"
        title="流程图"
        append-to-body
        :show-footer="true"
        :showFooterOk="false"
        cancelText="关闭"
        @cancel="data.showFlowPic = false"
        @closed="data.showFlowPic = false"
      >
        <FlowPhoto
          :def-flow-id="data.currJob.defFlowId"
          :flow-inst-id="data.currJob.flowInstId"
          @close="data.showFlowPic = false"
        />
      </CommonDialog>
    </div>
  </div>
</template>

<script setup lang="ts" name="TaskTodo">
import { BasicTableProps, useTable } from "@/hooks/table";
import { useMessage, useMessageBox } from "@/hooks/message";
import { useUserStore } from "@/store/modules/user";
import * as doJob from "@/api/flow/task/index";
import { queryTodoDetail, queryTodoPage } from "@/api/flow/taskquery/index";
import { translate } from "@/plugins/i18n";
import { isBlank } from "@/utils/validate";
import { getTableHeight } from "@/utils/util";
import { reactive, ref } from "vue";
import CommonSelect from "@/components/commonSelect.vue";
import RightToolBar from "@/components/rightToolBar.vue";
import FlowPhoto from "@/components/flow/flowPhoto.vue";
import AuditorChoose from "@/components/flow/AuditorChoose.vue";
import HandleJob from "@/components/flow/flowJobHandle.vue";
import CommentTimeLine from "@/components/flow/flowCommentTimeline.vue";

const userStore = useUserStore();

// 定义变量内容
const queryRef = ref();
const tableRef = ref(null);
const auditorChooseRef = ref(null);
const mounted = ref(false);

const tableOptions: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    initiatorId: "",
    defFlowId: "",
    flowNodeId: "",
    nodeJobId: ""
  },
  autoLoad: true,
  height: getTableHeight(1, true, true),
  queryFunction: queryTodoPage,
  descs: ["start_time"]
});

const {
  tableStyle,
  queryTableData,
  handleSelectionChange,
  handleResetQuery,
  handleRowClick,
  handleSizeChange,
  handleCurrentChange,
  handleSortChange,
  downBlobFile
} = useTable(tableOptions, tableRef);

const data = reactive({
  showSearch: true,
  // 0、转办 1、下一办理人 2、反签收
  appointType: undefined,
  currJob: undefined,
  job: {
    id: "",
    orderInstId: "",
    defFlowId: "",
    flowInstId: "",
    flowKey: "",
    formId: "",
    flowName: "",
    runNodeId: "",
    defNodeFormMode: "normal",
    jobBtns: []
  },
  showHandleJob: false,
  showComment: false,
  showFlowPic: false,
  showJumpToRunNode: false,
  showToRunNode: false,
  showJobSignature: false,
  jobSignatureTitle: undefined
});

const handleToggleSearch = () => {
  if (data.showSearch) {
    tableOptions.height = getTableHeight(1, true, true);
  } else {
    tableOptions.height = getTableHeight(0, true, true) + 5;
  }
};

const methods = {
  handleJob(row: any, saveRead: boolean) {
    const query = { id: row.id };
    queryTodoDetail(query).then(response => {
      const todoDetail = response.data;
      data.currJob = response.data;
      data.job.id = data.currJob.id;
      data.job.jobBtns = data.currJob.jobBtns;
      data.job.runNodeId = data.currJob.runNodeId;
      data.job.orderInstId = todoDetail.runFlow
        ? todoDetail.runFlow.orderInstId
        : "";
      data.job.defFlowId = todoDetail.defFlowId;
      data.job.flowInstId = todoDetail.flowInstId;
      data.job.flowKey = todoDetail.flowKey;
      data.job.flowName = todoDetail.runFlow ? todoDetail.runFlow.flowName : "";
      data.job.formId = todoDetail.runFlow ? todoDetail.runFlow.formId : "";
      data.job.defNodeFormMode = todoDetail.defNodeFormMode;
      if ("1" === data.currJob.status) {
        useMessage().warning("当前任务已被其他办理人审批");
        queryTableData();
      } else {
        data.showHandleJob = true;
        if (saveRead) {
          doJob.isRead({ id: data.currJob.id }).then(() => {
            row.isRead = "1";
          });
        }
      }
    });
  },
  handleAuditorConfirm(auditor: {
    auditorType: string;
    userId: string;
    roleId: string;
  }) {
    if (data.appointType === "0") {
      methods.handleTurnConfirm(auditor);
    }
  },
  handleTurnJob(row) {
    data.currJob = row;
    data.appointType = "0";
    auditorChooseRef.value.show();
  },
  handleComment(row) {
    data.currJob = row;
    data.showComment = true;
  },
  handleFlowPic(row) {
    mounted.value = true;
    data.currJob = row;
    data.showFlowPic = true;
  },
  onHandleJobComplete() {
    queryTableData();
    data.showHandleJob = false;
  },
  // 反签收任务
  handleSignOffJob(row) {
    let msg = "";
    if (isBlank(row.roleId)) {
      msg = "是否确认反签收当前任务, 将放回公共任务列表?";
    } else {
      msg = "是否确认反签收当前任务, 将重置为角色任务?";
    }
    useMessageBox()
      .confirm(msg)
      .then(() => {
        const obj = {
          id: row.id,
          signType: "0",
          roleId: isBlank(row.roleId) ? null : row.roleId
        };
        doJob.signForJob(obj).then(() => {
          useMessage().success("操作成功");
          queryTableData();
        });
      });
  },
  //签收任务
  handleSignOnJob(row) {
    const obj = { id: row.id, signType: "1" };
    doJob.signForJob(obj).then(() => {
      useMessage().success("操作成功");
      queryTableData();
    });
  },
  // 挂起激活任务
  handleSuspension(row, suspension) {
    if (suspension === "0") {
      const params = { id: row.id, suspension: suspension };
      doJob.suspension(params).then(res => {
        if (res.code === 200) {
          useMessage().success("操作成功");
          queryTableData();
        } else {
          useMessage().error(res.msg);
        }
      });
    } else {
      // 增加挂起原因
      useMessageBox()
        .prompt("请输入挂起原因")
        .then(({ value }) => {
          const params = {
            id: row.id,
            suspension: suspension,
            suspensionReason: value
          };
          doJob.suspension(params).then(res => {
            useMessage().success("操作成功");
            queryTableData();
          });
        });
    }
  },
  // 转办任务
  handleTurnConfirm(auditor: {
    auditorType: string;
    userId: string;
    roleId: string;
  }) {
    useMessageBox()
      .confirm(`是否确认转办任务?`)
      .then(() => {
        const params = { id: data.currJob.id, userId: auditor.userId };
        doJob.turnRunJob(params).then(res => {
          if (res.code === 200) {
            useMessage().success("操作成功");
            queryTableData();
          } else {
            useMessage().error(res.msg);
          }
        });
      });
  }
};
</script>

<style lang="scss" scoped>
@use "@/assets/style/design/flow-drawer.scss";
</style>
/@/api/flow/task
